package com.pan.service;

import com.pan.dao.User;
import com.pan.dao.UserDAO;
import com.pan.dao.UserDAOImpl;
import com.pan.util.TokenGenerator;
import org.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.sql.SQLException;
import java.util.concurrent.TimeUnit;


@WebServlet("/login")
public class Login extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String email = req.getParameter("email");
        String password = req.getParameter("password");

        boolean flag = true;
        String errMsg = "";

        UserDAO userDAO = UserDAOImpl.getInstance();
        User user = userDAO.getUserByEmail(email);
        if (user != null && user.getPassword().equals(password)) {
            // 生成 token 和过期时间（7 天后过期）
            String token = TokenGenerator.generateToken();
            long expiryMillis = System.currentTimeMillis() + TimeUnit.DAYS.toMillis(7);
            Timestamp expiry = new Timestamp(expiryMillis);

            // 将 token 存入数据库
            try {
                userDAO.saveToken(user.getId(), token, expiry);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        } else {
            flag = false;
            errMsg = "邮箱或密码错误";
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("status", flag ? "success" : "error");
        jsonObject.put("message", flag ? "登录成功" : errMsg);
        jsonObject.put("token", flag ? userDAO.getUserById(user.getId()).getToken() : null);
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");
        PrintWriter out = resp.getWriter();
        out.write(jsonObject.toString());
        out.flush();
        out.close();
    }
}